<template>
  <div>
  <el-dialog
    title="上报改善点"
    :visible.sync="dialogVisible"
    :modal="true"
    :appendToBody="true"
    width="680px"
    v-dialog-drag
    :close-on-click-modal="false"
    top="5vh"
    @close="handleClose()"
    @open="handleOpen()"
  >
    <el-form :model="form" :rules="rules" ref="ruleForm" label-width="110px">
      <el-form-item label="所属工厂" prop="branchcodeName">
        <el-input type="text" v-model="form.branchcodeName" disabled placeholder="请选择所属工厂"></el-input>
      </el-form-item>

      <el-form-item label="所属车间" prop="workshopId">
        <el-select
          v-model="form.workshopId"
          placeholder="请选择车间"
          clearable
          size="small"
          @change="handleWorkshop"
        >
          <el-option
            v-for="item in workshopList"
            :key="item.workshopId"
            :label="item.workshopName"
            :value="item.workshopId"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="所属产线" prop="lineId">
        <el-select
          v-model="form.lineId"
          placeholder="请选择产线"
          clearable
          size="small"
          @change="handleLine"
        >
          <el-option
            v-for="item in lineList"
            :key="item.lineId"
            :label="item.lineName"
            :value="item.lineId"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="改善点名称" prop="reportTaskName">
        <el-input type="text" v-model="form.reportTaskName" placeholder="请输入改善点名称"></el-input>
      </el-form-item>

      <el-form-item label="改善点内容" prop="reportTaskDes">
        <el-input
          type="textarea"
          :autosize="{ minRows: 2}"
          maxlength="200"
          show-word-limit
          placeholder="请输入改善点内容"
          v-model="form.reportTaskDes">
        </el-input>
      </el-form-item>

      <el-form-item label="审核人" prop="checkName">
        <el-input type="text" v-model="form.checkName" placeholder="请选择审核人" readonly>
          <el-button slot="append" icon="el-icon-search" @click="openUserDialog"></el-button>
        </el-input>
      </el-form-item>

      <el-form-item label="附件">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :headers="{Authorization:token}"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-upload='beforeAvatarUpload'
          :on-success='handleSuccess'
          :accept="acceptFile"
          multiple
          :limit="10"
          :on-exceed="handleExceed"
          :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">请上传大小不超过 5MB 格式为 jpg/png/gif/pdf/doc/docx/xls/xlsx/ppt/pptx/jpeg/zip 的文件，最多10个。</div>
        </el-upload>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" :loading="saveloading" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
  <userList
    :visibles.sync="userDialog.visible"
    :multiple="false"
    :defaultValues="userDialog.defaulSelectUsers"
    :branchinnercode="userDialog.branchinnercode"
    @closeDialog="closeUserDialog"
  ></userList>
  </div>
</template>
<script>
  import { getToken } from '@/utils/auth'
  import { fileTypes } from '@/utils/file'
  import service from "../../../utils/request";
  import { GEN_SERVER } from '@/config/baseUrl'
  import {reportAdd} from "@/api/leanTask/report";
  import {mapGetters} from "vuex";
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    row: {
      type: Object,
      default: ()=>{}
    }
  },
  data() {
    return {
      form: {
        factoryDeptCode:null,
        factoryDeptId:null,
        branchcodeName:null,
        workshopId:null,
        lineId:null,
        reportTaskName:null,
        reportTaskDes:null,
        checkName:null,
        checkUserName:null,
        fileIds:[]
      },
      fileTypes,
      fileList:[],
      workshopList:[],
      lineList:[],
      rules: {
        branchcodeName: [
          { required: true, message: "请选择所属工厂", trigger: "change" },
        ],
        reportTaskName: [
          { required: true, message: "请输入改善点名称", trigger: "blur" },
          { max: 30, message: "改善点名称不能超过30个字符", trigger: "blur" }
        ],
        reportTaskDes: [
          { required: true, message: "请输入改善点内容", trigger: "blur" },
          { max: 200, message: "改善点内容不能超过200个字符", trigger: "blur" }
        ],
        checkName: [
          { required: true, message: "请选择审核人", trigger: "change" }
        ]
      },
      userDialog: {
        visible: false,
        defaulSelectUsers:[],
        branchinnercode:null
      },
      saveloading: false
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val)
      },
      get() {
        return this.visible
      }
    },
    ...mapGetters([
      'baseDeptId',
      'baseDeptName',
      'baseDeptCode',
      'allList'
    ]),
    uploadUrl(){
      return service.baseURL + GEN_SERVER['form-server'] + '/refine/report/upload'
    },
    token() {
      return 'Bearer ' + getToken()
    },
    acceptFile(){
      return Object.values(this.fileTypes).join(",")
    }
  },
  methods: {
    handleClose() {
      this.saveloading = false
      this.resetFormData()
    },

    handleOpen() {
      this.resetFormData();
      const result = this.getOwnFirstLine()
      this.form.branchcodeName = this.baseDeptName;
      this.form.factoryDeptCode = this.baseDeptCode;
      this.form.factoryDeptId = this.baseDeptId;
      if(this.form.factoryDeptId){
        const factoryItem = this.allList.find(ele => ele.factoryDeptCode === this.form.factoryDeptCode);
        this.workshopList = factoryItem?.workshopVos ? factoryItem?.workshopVos : [];
      }
      this.form.workshopId = result[1]?.workshopId;
      if(this.form.workshopId){
        this.handleWorkshop(this.form.workshopId)
      }
      this.form.lineId = result[2]?.lineId;
    },

    handleSubmit() {
      this.saveloading = true
      this.$refs.ruleForm
      .validate((flag) => {
        if (flag) {
          reportAdd(this.form).then(res => {
            if (res.code == 200) {
              this.msgSuccess("操作成功")
              this.$emit("submit-success")
              this.dialogVisible = false
            } else {
              this.msgError(res.msg || "操作失败")
            }
            this.saveloading = false
          }).catch(() => {
            this.saveloading = false
          })
        } else {
          this.saveloading = false
        }
      })
    },

    //打开人员选择器
    openUserDialog() {
      this.userDialog.defaulSelectUsers= [];
      this.userDialog.branchinnercode = this.baseDeptId;
      if(this.form.checkUserName){
        this.userDialog.defaulSelectUsers.push({
          username:this.form.checkUserName,
          realname:this.form.checkName
        })
      }
      this.userDialog.visible = true
    },

    //选择车间,获取产线数据
    handleWorkshop(val,key){
      const workshopItem = this.workshopList.find(ele => ele.workshopId === val);
      this.lineList = workshopItem?.productionLineVos ? workshopItem?.productionLineVos : [];
      if(key != "init"){
        this.form.lineId = null;
      }
    },
    handleLine(val){
      this.form.lineId = val;
      this.$forceUpdate()
    },

    closeUserDialog(list){
      if(list?.length){
        this.form.checkUserName = list.map(item => item.username).join();
        this.form.checkName = list.map(item => item.realname).join()
      }else{
        this.form.checkUserName = null;
        this.form.checkName = null;
      }
    },

    handleSuccess(response, file, fileList){
      this.fileList = fileList;
      this.form.fileIds = fileList.map(ele => ele.response?.data)
    },

    handleRemove(file, fileList) {
      this.fileList = fileList;
      if(fileList?.length){
        this.form.fileIds = fileList.map(ele => ele.response?.data)
      }else{
        this.form.fileIds = []
      }
    },

    getObjectURL(file) {
      var url = null;
      if (window.createObjectURL != undefined) {
        url = window.createObjectURL(file);
      } else if (window.URL != undefined) {
        url = window.URL.createObjectURL(file);
      } else if (window.webkitURL != undefined) {
        url = window.webkitURL.createObjectURL(file);
      }
      return url;
    },

    handlePreview(file) {
      var previewUrl = this.getObjectURL(file.raw);
      window.open(previewUrl)
    },

    beforeAvatarUpload(file){
      if(!this.acceptFile.includes(file.type)){
        this.msgWarning("暂不支持上传该格式文件");
        return false
      }
      if(file.size / 1024 / 1024  > 5){
        this.msgWarning("上传的附件大小不得超过5M");
        return false
      }
    },

    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 10个文件，本次选择了 ${files.length} 个文件`);
      return false
    },

    resetFormData() {
      this.$refs.ruleForm?.resetFields()
      this.form = {
        factoryDeptCode:null,
        factoryDeptId:null,
        workshopId:null,
        lineId:null,
        reportTaskName:null,
        reportTaskDes:null,
        checkName:null,
        checkUserName:null,
        fileIds:[]
      };
      this.fileList = [];
    },
  }
};
</script>
<style lang="scss" scoped>
.el-form {
  // display: flex;
  // justify-content: space-between;
  // flex-flow: wrap;
  // .el-form-item {
  //   width: 49%;
  // }
  .el-date-editor.el-input,
  .el-select {
    width: 100%;
  }
}
.tool-bar{
  margin-bottom:20px
}
</style>
